#include "clientwindow.h"

// Local Includes
#include "clientnetengine.h"
#include "connectreplymsg.h"
#include "clientconnection.h"
#include "clientnetengine.h"
#include "netmsg.h"

#include "configdlg.h"

/////////////////////////////////////////////////////////////////////
// Construction & Destruction
/////////////////////////////////////////////////////////////////////
CClientWindow::CClientWindow(QWidget *pParent/* = NULL*/, Qt::WFlags windowFlags/* = 0*/)
	: QMainWindow(pParent, windowFlags),
	  m_pClientConnection(new CClientConnection(this))
{
	setupUi(this);

	// Signals & Slots.
	connect(m_pClientConnection, SIGNAL(connected()), this, SLOT(onClientConnected()));
	connect(action_Configure_Client, SIGNAL(triggered(bool)), this, SLOT(onConfigureClient()));


	// Automatically connect on startup.
	// This will run on a seperate thread.
	m_pClientConnection->connectToHost(tr("127.0.0.1"), 16000);
}

/////////////////////////////////////////////////////////////////////
// Private Slots
/////////////////////////////////////////////////////////////////////
void CClientWindow::onClientConnected()
{
	qDebug("onClientConnected");

	// Now we know the clientEngine has been created, we can hook up to it.
	connect(m_pClientConnection->GetClientNetEngine(), SIGNAL(newMessage()), this, SLOT(onClientNewMessage()));

	// Let's "register" with the server.
	m_pClientConnection->connectToServer("UserName", "PasswordHash");
}

void CClientWindow::onClientNewMessage()
{
	qDebug("onClientNewMessage");
	CNetMsg *pMsg = m_pClientConnection->GetClientNetEngine()->getMessage();

	switch(pMsg->getType())
	{
		case CNetMsg::MSG_TYPE_CONNECT_REPLY:
		{
			// The reply from the server will contain the pluginManager config.
			// For now, we show this in the UI.
			const CConnectReplyMsg *const pReplyMsg = static_cast<CConnectReplyMsg*>(pMsg);

			if(pReplyMsg)
			{
				configWidget->setConfigPayload(pReplyMsg->getConfigPayload());
			}

			break;
		}

		default:
			break;
	}

	delete pMsg;
}


void CClientWindow::onConfigureClient()
{
	CConfigDlg dlg(this);
	dlg.exec();
}

/////////////////////////////////////////////////////////////////////
